package com.yb0os1.Iterator;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class UserFile implements Iterable<User> {
    private final File file;
    private int line;

    public UserFile(File file) {
        this.file = file;
    }

    public UserFile(File file, int line) {
        this.file = file;
        this.line = line;
    }

    @Override
    public Iterator<User> iterator() {
        return new UserFileIterator();
    }

    class UserFileIterator implements Iterator<User> {

        private int cursor;
        private final int batchLineSize = UserFile.this.line == 0 ? 10 : UserFile.this.line;
        private int currentLine;
        private long pos = 0L;
        int count = 1;//记录读取的次数

        private List<User> userList = readPart();

        private List<User> readPart() {
            try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
                raf.seek(pos);
                List<User> tmp = new ArrayList<>();
                while (currentLine < batchLineSize) {
                    String line = raf.readLine();
                    if (line == null) {
                        break;
                    }
                    line = new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                    String[] split = line.substring(1, line.length() - 1).split(",");
                    User user = new User(split[0], Integer.parseInt(split[1]));
                    tmp.add(user);
                    currentLine++;
                }
                currentLine = 0;
                pos = raf.getFilePointer();
                System.out.println("这是读取文件的第" + count++ + "次");
                return tmp;
            } catch (Exception e) {
                return Collections.emptyList();
            }
        }


        @Override
        public boolean hasNext() {
            if (cursor == userList.size()) {
                cursor = 0;
                userList = readPart();
            }
            return cursor != userList.size();
        }

        @Override
        public User next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return userList.get(cursor++);
        }
    }
}
